package com.sgb.member.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityInviterOrApplyBinding;
import com.sgb.member.databinding.ActivityMemberBusinessBinding;
import com.sgb.member.ui.fragment.MemberInviteOrApplyApprovalFragment;
import com.sgb.member.ui.fragment.MemberInviteOrApplyFragment;
import com.sgb.member.ui.fragment.MemberInviteOrApplyRecordFragment;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;

import java.util.ArrayList;

@Route(path = MemberConfig.ROUTE_INVITE_APPLY)
public class MemberInviteOrApplyActivity extends AppActivity {

//    private ActivityMemberBusinessBinding mBinding;
    private ActivityInviterOrApplyBinding mBinding;
    private final SparseArray<String> mSearchList = new SparseArray<>();
    private final SparseArray<String> mSearchHintList = new SparseArray<>();
    private ArrayList<Fragment> mFragments;

    boolean isManagePager;

    /**
     * @param isManagePager true : 个人中心邀请或申请管理， false : 会员首页邀请加盟或申请加盟
     * @param curPage       0 邀请会员/邀请记录；1申请会员/申请记录
     * @param index         ViewPager 下标 0 : 邀请/申请会员列表 1: 邀请/申请会员记录列表 2: 加盟审批记录页面
     */
    private static void start(Context context, boolean isManagePager, int curPage, int index) {
        Intent intent = new Intent(context, MemberInviteOrApplyActivity.class);
        intent.putExtra("IS_MANAGE_PAGER", isManagePager);
        intent.putExtra("CUR_PAGE", curPage);
        intent.putExtra("INDEX", index);
        context.startActivity(intent);
    }

    /**
     * @param curPage 0 邀请会员/邀请记录；1申请会员/申请记录
     */
    public static void startInviteOrApply(Context context, int curPage) {
        start(context, false, curPage, 0);
    }

    /**
     * @param curPage 0 邀请会员/邀请记录；1申请会员/申请记录
     */
    public static void startInviteOrApplyRecord(Context context, int curPage) {
        start(context, false, curPage, 1);
    }

    /**
     * @param curPage 0 邀请会员/邀请记录；1申请会员/申请记录
     */
    public static void startInviteOrApplyApproval(Context context, int curPage) {
        start(context, false, curPage, 2);
    }

    /**
     * @param curPage 0 邀请会员/邀请记录；1申请会员/申请记录
     */
    public static void startManage(Context context, int curPage) {
        start(context, true, curPage, 0);
    }

    public static void startManage2(Context context, int curPage) {
        start(context, false, curPage, 0);
    }


    @Override
    protected void initView() {
        isManagePager = getIntent().getBooleanExtra("IS_MANAGE_PAGER", false);
        // 0 邀请会员；1申请会员;
        int mCurPage = getIntent().getIntExtra("CUR_PAGE", 0);
        int index = getIntent().getIntExtra("INDEX", 0);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_inviter_or_apply);
        // 类型 0个人 1企业 2团队
        int comType = MemberConfig.getInstance().getComType();
        String[] tabs = null;
        mFragments = new ArrayList<>();
        if (isManagePager) {
            if (mCurPage == 0) {//邀请
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    tabs = new String[]{"邀请记录"};
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                } else {
                    tabs = new String[]{"邀请记录", "邀请审批记录"};
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyApprovalFragment.newInstance(mCurPage));
                }
            } else if (mCurPage == 1) {//申请
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    tabs = new String[]{"申请记录"};
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                } else {
                    tabs = new String[]{"申请记录", "加盟审批记录"}; //  "加盟审批记录"
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyApprovalFragment.newInstance(mCurPage));
                }
            }
        } else {
            if (mCurPage == 0) {
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    tabs = new String[]{"邀请加盟", "邀请记录"};
                    mFragments.add(MemberInviteOrApplyFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                } else {
                    tabs = new String[]{"邀请加盟", "邀请记录", "邀请审批记录"};
                    mFragments.add(MemberInviteOrApplyFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyApprovalFragment.newInstance(mCurPage));
                }
            } else if (mCurPage == 1) {
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    tabs = new String[]{"申请加盟", "申请记录"};
                    mFragments.add(MemberInviteOrApplyFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                } else {
                    tabs = new String[]{"申请加盟", "申请记录", "申请审批记录"}; //  "加盟审批记录"
                    mFragments.add(MemberInviteOrApplyFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyRecordFragment.newInstance(mCurPage, comType));
                    mFragments.add(MemberInviteOrApplyApprovalFragment.newInstance(mCurPage));
                }
            }
        }
        if (tabs == null) {
            finish();
            return;
        }
        for (int i = 0; i < tabs.length; i++) {
            mSearchList.put(i, "");
            mSearchHintList.put(i, "请输入客户名称");
        }
        SlidingFragmentPagerAdapter mPagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, tabs);
        mBinding.vp.setOffscreenPageLimit(tabs.length);
        mBinding.vp.setAdapter(mPagerAdapter);
        if (mFragments.size() > 1) {
            mBinding.tabLayout.setVisibility(View.VISIBLE);
            mBinding.tabLayout.setupWithViewPager(mBinding.vp);
            mBinding.tabLayout.setNormalColor(R.color.color_main_bg);
            mBinding.tabLayout.setSelectColor(R.color.color_white);
            mBinding.tabLayout.setNormalSize(14);
            mBinding.tabLayout.setSelectSize(16);
            mBinding.tabLayout.setTabMode(TabLayout.MODE_FIXED);
            mBinding.tabLayout.addOnTabSelectedListener(tabs, new XCustomTabLayout.SimpleSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    String s = mSearchList.get(tab.getPosition());
                    mBinding.activityBar.etView.setHint(mSearchHintList.get(tab.getPosition()));
                    mBinding.activityBar.etView.setText(s);
                    mBinding.vp.setCurrentItem(tab.getPosition());
                }
            });
            mBinding.vp.setCurrentItem(index, true);
        } else {
            mBinding.tabLayout.setVisibility(View.GONE);
        }
        initSearchView();
    }

    private String mSearchText = ""; // 搜索内容

    private void initSearchView() {
        mBinding.activityBar.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        String hint = mSearchHintList.get(mBinding.tabLayout.getSelectedTabPosition());
        mBinding.activityBar.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.activityBar.etView.setHint(hint);
        mBinding.activityBar.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), hint);
                        return true;
                    }
                    /*if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入不同的搜索内容");
                        return true;
                    }*/
                    mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                    loadSearchData();
                }
                return false;
            }
        });
        mBinding.activityBar.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s) || s.length() == 0) {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
                } else {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBinding.activityBar.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchText = "";
                mBinding.activityBar.etView.setText("");
                loadSearchData();
            }
        });
        mBinding.activityBar.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mSearchText)) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), hint);
                        return;
                    }
                }
                if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                    MToast.showToast(getActivity(), "请输入不同的搜索内容");
                    return;
                }
                mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                loadSearchData();
            }
        });
        mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
    }

    public String getSearchText() {
        int tabPosition = mBinding.vp.getCurrentItem();
        return mSearchList.get(tabPosition);
    }

    private void loadSearchData() {
        int tabPosition = mBinding.vp.getCurrentItem();
        mSearchList.put(tabPosition, mSearchText);
        Fragment fragment = mFragments.get(tabPosition);
        if (fragment instanceof MemberInviteOrApplyFragment) {
            ((MemberInviteOrApplyFragment) fragment).loadData(false);
        }
        if (fragment instanceof MemberInviteOrApplyRecordFragment) {
            ((MemberInviteOrApplyRecordFragment) fragment).loadData(false);
        }
        if (fragment instanceof MemberInviteOrApplyApprovalFragment) {
            ((MemberInviteOrApplyApprovalFragment) fragment).loadData(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_SERVICE) {
            if (data != null) {
                boolean jumpRecord = data.getBooleanExtra(MemberConfig.JUMP_RECORD, false);
                if (jumpRecord) {
                    if (mBinding.vp.getCurrentItem() != 1) {
                        mBinding.vp.setCurrentItem(1);
                    }
                }
                boolean jumpRecordApproval = data.getBooleanExtra(MemberConfig.JUMP_RECORD_APPROVAL, false);
                if (jumpRecordApproval) {
                    if (mBinding.vp.getCurrentItem() != 2) {
                        mBinding.vp.setCurrentItem(2);
                    }
                }
            }
            refreshData();
        }
    }

    private void refreshData() {
        mSearchList.clear();
        mSearchText = "";
        mBinding.activityBar.etView.setText("");
        for (Fragment fragment : mFragments) {
            if (fragment instanceof MemberInviteOrApplyFragment) {
                ((MemberInviteOrApplyFragment) fragment).loadData(false);
            }
            if (fragment instanceof MemberInviteOrApplyRecordFragment) {
                ((MemberInviteOrApplyRecordFragment) fragment).loadData(false);
            }
            if (fragment instanceof MemberInviteOrApplyApprovalFragment) {
                ((MemberInviteOrApplyApprovalFragment) fragment).loadData(false);
            }
        }
    }
}
